<template>
  <div class="activatePop" v-if="activatePopShow" @click.stop="close">
    <div class="activateBox">
      <div class="membership">
        <!-- <img class="right" src="../../../assets/rem.jpg" alt="" /> -->
        <div class="closePay">微信扫码识别支付</div>
        <div class="">
          <div
            v-if="!codeShow"
            class="qrcode right"
            id="exportCanvas"
            ref="qrCodeUrl"
            @click.stop=""
            @touchstart="touchStart()"
            @touchend="touchEnd()"
          ></div>
          <img :src="posterUrl" alt="" />
        </div>

        <div class="" v-if="codeShow">
          <div class="longPress" @click.stop="exportDisCopy('exportCanvas', '宇时会员二维码')">长按识别二维码</div>
          <div class="closeWin">支付成功后自动关闭窗口</div>
          <div class="payNum">{{ payObjComp.money }}元</div>
        </div>

        <div class="message-text" v-else>
          <div class="loading"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
// import {VxeWebSocketMixins} from '@/mixins/WebsocketMixin'
import Vue from 'vue'
import store from '@/store/'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mapActions, mapGetters, mapState } from 'vuex'
import { exportDis } from '@/utils/util'
import html2canvas from 'html2canvas' //html转图片
//所需页面导入
import QRCode from 'qrcodejs2'
export default {
  name: 'ConTract',
  // mixins: [VxeWebSocketMixins],
  components: {},
  props: {
    payObj: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      posterUrl: '',
      activatePopShow: false,
      confirmLoading: false,
      codeShow: false,
      dliUrl: '',
      codeId: '',
      lockReconnect: false,
      timer: '',
    }
  },
  computed: {
    payObjComp() {
      return this.payObj
    },
  },
  watch: {
    payObjComp: {
      handler(newVal, oldVal) {},
      deep: true,
      immediate: true,
    },
  },
  created() {},

  mounted() {},
  methods: {
    ...mapGetters(['userInfo']),
    // exportDis() {
    //   console.log('宇时会员二维码',exportDis('exportCanvas', '宇时会员二维码'))
    //   return
    //   exportDis('exportCanvas', '宇时会员二维码')
    // },
    exportDisCopy(domId, realname) {
      let dom = document.getElementById(domId)
      html2canvas(dom, {
        allowTaint: false, // 是否允许跨域图像污染画布
        useCORS: true, // 使用CO RS从服务器加载图像，必须为true否则img图片可能显示不出来
        dpi: window.devicePixelRatio * 4, //将分辨率提高到特定的DPI 提高四倍
        scale: 4, //按比例增加分辨率
        // x: 裁剪画布x坐标,
        // y: 裁剪画布y坐标,
      }).then((canvas) => {
        this.posterUrl = canvas.toDataURL()
      })
    },
    touchEnd() {
      //手指离开
      clearTimeout(this.timer)
    },
    touchStart() {
      //手指触摸
      clearTimeout(this.timer) //再次清空定时器，防止重复注册定时器
      this.timer = setTimeout(() => {
        this.downloadIamge(this.dliUrl, 'pic')
      }, 1000)
    },
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      let image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = () => {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        let url = canvas.toDataURL('image/png') //得到图片的base64编码数据
        let a = document.createElement('a') // 生成一个a元素
        let event = new MouseEvent('click') // 创建一个单击事件
        a.download = name || 'photo' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    creatQrCode(url) {
      new QRCode(this.$refs.qrCodeUrl, {
        text: url, // 需要转换为二维码的内容
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      })
    },
    apiPayment(id) {
      this.codeShow = false
      getAction('/packagerecharge/packageRecharge/payment', { id: id })
        .then((res) => {
          console.log('pay', res)
          this.creatQrCode(res.result)
          this.dliUrl = res.result
          this.codeShow = true
          this.exportDisCopy('exportCanvas', '宇时会员二维码')
          this.initWebSocket()
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    close() {
      this.activatePopShow = false
      this.websock.close() //关闭websocket
    },
    generatedBtnProp() {
      let obj = {
        role: this.models.role,
        contractType: this.models.contractType,
        content: this.models.content,
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('appApiAsk', 1, obj)
        } else {
          this.$emit('appApiAsk', 2, obj)
        }
      })
    },

    initWebSocket: function () {
      let token = Vue.ls.get(ACCESS_TOKEN)
      console.log('token', token)
      console.log('------------WebSocket连接成功')
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id
      // if (!this.socketUrl.startsWith('/')) {
      //   this.socketUrl = '/' + this.socketUrl
      // }
      // if (!this.socketUrl.endsWith('/')) {
      //   this.socketUrl = this.socketUrl + '/'
      // }
      // var url =
      //   window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') +
      //   this.socketUrl +
      //   userId +
      //   '/' +
      //   token
      var url =
        window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId
      console.log('url', url)
      //update-begin-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      this.websock = new WebSocket(url, [token])
      //update-end-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function () {
      console.log('WebSocket连接成功')
    },
    websocketOnerror: function (e) {
      console.log('WebSocket连接发生错误，第%s次', this.wsConnectErrorTime)

      this.wsConnectErrorTime = this.wsConnectErrorTime + 1
      if (this.wsConnectErrorTime > 5) {
        console.log('WebSocket连接错误超过5次，就不再重新连了！')
        this.lockReconnect = true
        return
      }

      this.reconnect()
    },
    websocketOnmessage: function (e) {
      console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') //解析对象
      if (data.msgTxt == '200') {
        this.close()
        this.codeShow = false
        this.$notification.success({
          message: '支付成功',
        })
        this.$store.dispatch('userLimitList', { userId: this.userInfo().id })
      } else {
        this.$notification.error({
          message: '支付失败',
        })
      }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      console.info('WebSocket已关闭...')
      this.reconnect()
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
    reconnect() {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      // setTimeout(function () {
      //   console.info('尝试重连...')
      //   that.initWebSocket()
      //   that.lockReconnect = false
      // }, 5000)
    },
  },
}
</script>

<style lang="less" scoped>
.activatePop {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  overflow: auto;
  .activateBox {
    width: 500px;
    position: relative;
    top: 20%;
    left: 50%;
    border: 1px solid #ccc;
    margin-left: -250px;
    background: white;
    border-radius: 10px;
    img {
      width: 100%;
    }
    .membership {
      padding: 44px 10px 18px 10px;
      display: flex;
      justify-content: center;
      flex-direction: column;
      .closePay {
        text-align: center;
        font-weight: bold;
        cursor: pointer;
        font-size: 20px;
        margin-bottom: 20px;
      }
      .payNum {
        text-align: center;
        font-weight: bold;
        cursor: pointer;
        font-size: 22px;
        color: red;
      }
    }
  }
}

/deep/.qrcode {
  display: flex;
  justify-content: center;
  img {
    width: 51%;
    margin: auto;
  }
}

.message-text {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: center;
}
.loading {
  width: 50px;
  height: 50px;
  border: 2px solid #1890ff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate 0.75s linear infinite;
  float: right;
  margin-left: 4px;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

.longPress {
  display: none;
  text-align: center;
  margin-top: 5px;
  color: #0b9e12;
  font-weight: bold;
}
.closeWin {
  text-align: center;
  font-weight: bold;
  cursor: pointer;
  font-size: 14px;
  margin-top: 10px;
}
@media screen and (max-width: 767px) {
  .longPress {
    display: block;
  }
}
</style>